import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_adapter.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/attend_record_calendar_page.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_update_info/bean/company_person_info_bean.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_update_info/company_add_user_update_info_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_detail_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/ui/mark/matching_mark_list/matching_mark_list_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/mark_info_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 企业详情分组-列表项
///
/// @author: zengxiangxi
/// @createTime: 1/29/21 4:08 PM
/// @specialDemand:
class CompanyDetailByTypeListItemWidget extends StatefulWidget {
  final CompanyDetailByTypeListItemBean itemBean;

  final ValueChanged<CompanyDetailByTypeListItemBean> onDelete;

  final ValueChanged<CompanyDetailByTypeListItemBean> onRemove;

  final ValueChanged<CompanyDetailByTypeListItemBean> onEdit;

  final ValueChanged<CompanyDetailByTypeListItemBean> onFaceIgnore;
  final ValueChanged<CompanyDetailByTypeListItemBean> onFaceDelete;

  const CompanyDetailByTypeListItemWidget(
      {Key key,
      this.itemBean,
      this.onDelete,
      this.onRemove,
      this.onEdit,
      this.onFaceIgnore,
      this.onFaceDelete})
      : super(key: key);

  @override
  _CompanyDetailByTypeListItemWidgetState createState() => _CompanyDetailByTypeListItemWidgetState();
}

class _CompanyDetailByTypeListItemWidgetState extends State<CompanyDetailByTypeListItemWidget> {
  StreamSubscription _attendanceStreamSubscription;
  @override
  void initState() {
    super.initState();
    _attendanceStreamSubscription = VgEventBus.global.on<ArtificialAttendanceUpdateEvent>().listen((event) {
      if(widget?.itemBean?.fuid == event?.fuid){
        widget?.itemBean?.putpicurl = event?.headFaceUrl;
        widget?.itemBean?.napicurl = event?.headFaceUrl;
      }
      setState(() { });
    });
  }

  @override
  void dispose() {
    _attendanceStreamSubscription?.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          if (widget.itemBean?.isUnknow() ?? false) {
            bool result = await MatchingMarkListPage.navigatorPush(
                context,
                MarkInfoBean(
                  picurl: widget.itemBean?.pictureUrl,
                  fid: widget.itemBean?.fid,
                ));
            if (result ?? false) {
              //刷新
              CompanyDetailPageState.of(context).noticeRefreshHttp();
            }
            return;
          }
          PersonDetailPage.navigatorPush(context, widget.itemBean?.fuid,
              fid:widget?.itemBean?.fid,
              isEnActive: !(widget?.itemBean?.isAlive()??true));
          _setCacheUserInfo();
          // AttendRecordCalendarPage.navigatorPush(context,itemBean?.fuid);
        },
        onLongPress: () {
          if(!AppOverallDistinguish.comefromAiOrWeStudy()){return;}
          _pushMoreMenuDialog(context, widget.itemBean);
        },
        child: _toListItemWidget(context));
  }

  ///设置缓存用户
  void _setCacheUserInfo() {
    if(widget.itemBean==null){
      return;
    }
    // SharePreferenceUtil.putString(UserRepository.getInstance().getCompanyId(), userDataBean?.fuid);
    //查询缓存，缓存中有数据，在基础上存储
    SharePreferenceUtil.getStringList(UserRepository.getInstance().getCompanyId())
        .then((List<String> value) {
      List<String> fuids = value??[];
      if (!(fuids.contains(widget.itemBean?.fuid))) {
        fuids.add(widget.itemBean?.fuid);
        SharePreferenceUtil.putStringList(UserRepository.getInstance().getCompanyId(), fuids);
      }else{
        return;
      }
    });
  }

  Widget _toListItemWidget(BuildContext context) {
    return Container(
      height: 64,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      child: _toMainRowWidget(context),
    );
  }

  Widget _toMainRowWidget(BuildContext context) {
    return Row(
      children: <Widget>[
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Container(
            width: 36,
            height: 36,
            child: VgCacheNetWorkImage(
              showOriginEmptyStr(widget.itemBean?.putpicurl) ??
                  showOriginEmptyStr(widget.itemBean?.napicurl ?? "") ??
                  (widget.itemBean?.pictureUrl ?? ""),
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
              defaultErrorType: ImageErrorType.head,
              defaultPlaceType: ImagePlaceType.head,
            ),
          ),
        ),
        SizedBox(
          width: 10,
        ),
        Container(
          height: 36,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: (VgStringUtils.checkAllEmpty([
              widget.itemBean?.department?.trim(),
              // itemBean?.projectname?.trim(),
              // itemBean?.city?.trim(),
              widget.itemBean?.classname?.trim(),
              // itemBean?.coursename?.trim(),
            ]))
                ? MainAxisAlignment.center
                : MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  (widget.itemBean?.isUnknow() ?? false)
                      ? Text(
                          "未知",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: ThemeRepository.getInstance()
                                  .getMinorRedColor_F95355(),
                              fontSize: 15,
                              height: 1.2),
                        )
                      : CommonNameAndNickWidget(
                          name: widget.itemBean?.name,
                          nick: widget.itemBean?.nick,
                        ),
                  VgLabelUtils.getRoleLabel(widget.itemBean?.roleid) ?? Container(),
                  _toPhoneWidget(),
                ],
              ),
              if (!VgStringUtils.checkAllEmpty([
                widget.itemBean?.department?.trim(),
                // itemBean?.projectname?.trim(),
                // itemBean?.city?.trim(),
                widget.itemBean?.classname?.trim(),
                // itemBean?.coursename?.trim(),
              ]))
                Builder(builder: (BuildContext context) {
                  List<String> classListStr;
                  String classStr = widget.itemBean?.classname?.trim();
                  if(widget.itemBean?.classname != null){
                    classListStr = widget.itemBean?.classname?.trim()?.split(",");
                    if(classListStr?.length!=0){
                      if(classListStr?.length > 1){
                        classStr = _classStrSubstring(classListStr[0],classListStr[0]?.length,classListStr?.length);
                      }else if(classListStr?.length == 1){
                        classStr = classListStr[0];
                        // if(classListStr[0]?.length > 7){
                        //   classStr = (classListStr[0]?.substring(0,7)+"...");
                        // }else{
                        //   classStr = classListStr[0];
                        // }
                      }
                    }
                  }

                  return CommonConstraintMaxWidthWidget(
                    maxWidth: ScreenUtils.screenW(context)/2,
                    child: Text(
                      // (itemBean?.isUnknow() ?? false)
                      //     ? (VgDateTimeUtils.getFormatTimeStr(
                      //             itemBean?.lastPunchTime) ??
                      //         "")
                      //     : (StringUtils.isNotEmpty(itemBean?.phone)
                      //         ? "${itemBean.phone}"
                      //         : "暂无手机号码"),
                      VgStringUtils.getSplitStr([
                        widget.itemBean?.department?.trim(),
                        //项目和城市暂时不展示
                        // itemBean?.projectname?.trim(),
                        // itemBean?.city?.trim(),
                        classStr,
                        // itemBean?.coursename?.trim(),
                      ], symbol: "/"),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 12,
                      ),
                    ),
                  );
                }),
            ],
          ),
        ),
        Expanded(
          child: _toColumnWidget(),
        ),
        if (widget.itemBean?.isUnknow() ?? false)
          Container(
            width: 60,
            height: 28,
            margin: const EdgeInsets.only(left: 15),
            decoration: BoxDecoration(
              border: Border.all(color: VgColors.INPUT_BG_COLOR, width: 0.5),
              borderRadius: BorderRadius.circular(14),
            ),
            child: Center(
              child: Text(
                "标记",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 13,
                ),
              ),
            ),
          ),
      ],
    );
  }

  String _classStrSubstring(String str,int length,int classListLength){
    if(length > 7){
      return (str?.substring(0,7)+"...") + "等${classListLength }个班级";
    }else{
      return str + "等${classListLength}个班级";
    }
  }

  Widget _toColumnWidget() {
    return DefaultTextStyle(
      style: TextStyle(height: 1.2),
      child: Container(
        height: 36,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              height: 21,
              alignment: Alignment.centerLeft,
              child: Row(
                children: <Widget>[
                  Spacer(),
                  Text.rich(TextSpan(children: [
                    TextSpan(
                      text: "${VgStringUtils.subStringAndAppendSymbol(
                          _getAddOrMarkUserAndStatusStr(), 15,
                      symbol: "...") ?? ""}",
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 10,
                      ),
                    ),
                    TextSpan(
                      text: ((widget.itemBean?.isAlive() ?? true) || !UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition()) ? "" : "·",
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 10,
                      ),
                    ),
                    if (!(widget.itemBean?.isUnknow() ?? false) && UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition())
                      TextSpan(
                        text: (widget.itemBean?.isAlive() ?? true) ? "" : "未激活",
                        style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getMinorRedColor_F95355(),
                          fontSize: 10,
                        ),
                      ),
                  ]))
                ],
              ),
            ),
            // if (!VgStringUtils.checkAllEmpty([
            //   itemBean?.department?.trim(),
            //   itemBean?.projectname?.trim(),
            //   itemBean?.city?.trim(),
            // ]))
            Row(
              children: <Widget>[
                Spacer(),
                Text(
                  _getGroupAndIdStr(widget.itemBean?.groupName, widget.itemBean?.number) ??
                      "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 12,
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  String _getGroupAndIdStr(String groupName, String number) {
    if (StringUtils.isEmpty(groupName) && StringUtils.isEmpty(number)) {
      return null;
    }
    if (StringUtils.isNotEmpty(groupName) && StringUtils.isEmpty(number)) {
      return groupName;
    }
    if (StringUtils.isEmpty(groupName) && StringUtils.isNotEmpty(number)) {
      return number;
    }
    return groupName + "·" + number;
  }

  String _getAddOrMarkUserAndStatusStr() {
    if ((widget.itemBean?.isAlive() ?? false) && widget.itemBean.lastPunchTime != null) {
      return VgDateTimeUtils.getFormatTimeStr(widget.itemBean.lastPunchTime) + "刷脸";
    }
    if (StringUtils.isEmpty(widget.itemBean?.uname)) {
      return null;
    }
    StringBuffer stringBuffer = StringBuffer(widget.itemBean?.uname);

    /// tpe  00标记录入 01app手动添加
    if (!(widget.itemBean?.isMark() ?? false)) {
      stringBuffer.write("添加");
    } else {
      stringBuffer.write("标记");
    }
    return stringBuffer.toString();
  }

  ///弹出更多菜单弹窗
  void _pushMoreMenuDialog(
      BuildContext context, CompanyDetailByTypeListItemBean itemBean) {
    Map<String, VoidCallback> menuMap = Map();
    if (itemBean?.isUnknow() ?? false) {
      menuMap['忽略'] = () {
        widget.onFaceIgnore?.call(itemBean);
      };
      if(itemBean?.isSpecialList??false){
        menuMap['移除'] = () {
          widget.onRemove?.call(itemBean);
        };
      }else{
        menuMap['删除'] = () {
          widget.onFaceDelete?.call(itemBean);
        };
      }

    } else {
      if (VgRoleUtils.isHasEditForCompanyDetail(itemBean?.userid,itemBean?.roleid)) {
        menuMap['编辑'] = () {
          widget.onEdit?.call(itemBean);
        };
      }
      if (VgRoleUtils.isHasDeleteForCompanyDetail(
          itemBean?.userid, itemBean?.roleid)) {
        if(itemBean?.roleid!="99"){
          if(itemBean?.isSpecialList??false){
            menuMap['移除'] = () {
              widget.onRemove?.call(itemBean);
            };
          }else{
            menuMap['删除'] = () {
              widget.onDelete?.call(itemBean);
            };
          }

        }

      }
      if (menuMap == null || menuMap.isEmpty) {
        return;
      }
    }
    CommonMoreMenuDialog.navigatorPushDialog(context, menuMap);
  }

  Widget _toPhoneWidget() {
    return Offstage(
      offstage: widget.itemBean.phone == null || widget.itemBean.phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(widget.itemBean?.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }
}
